using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthSliderController : MonoBehaviour
{

    public Slider slider;
    public Transform targetTransform; // 目标GameObject的Transform
    public float minValue = 0f;
    public float maxValue = 1f;
    public int activedTime = 0;
    private void Start()
    {
        if (slider == null)
        {
            Debug.LogError("Slider reference is missing!");
            return;
        }

        // 设置Slider的初始值
        SetValue(1f);
    }

    private void Update()
    {
        // 使Slider一直跟随目标GameObject的Transform
        if (targetTransform != null)
        {
            slider.transform.position = Camera.main.WorldToScreenPoint(targetTransform.position);
        }
    }

    public void SetFollowAndValue(Transform transform, float value){
        targetTransform = transform;
        activedTime++;
        SetValue(value);
    }

    // 设置Slider的值，并根据值的变化调整颜色
    public void SetValue(float value)
    {
        // 限制值在[minValue, maxValue]范围内
        value = Mathf.Clamp(value, minValue, maxValue);

        // 设置Slider的值
        slider.value = value;

        // 根据值的变化调整颜色
        AdjustColor(value);
    }

    private void AdjustColor(float value)
    {
        // 根据值的范围从绿色（1）到红色（0）进行颜色渐变
        Color color = Color.Lerp(Color.red, Color.green, value);
        slider.fillRect.GetComponentInChildren<Image>().color = color;
    }
}

